<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">登录</h2>
      <div class="login-form">
        <input
            v-model="username"
            type="text"
            placeholder="请输入用户名"
            class="login-input"
        />
        <input
            v-model="password"
            type="password"
            placeholder="请输入密码"
            class="login-input"
        />
        <button @click="login" class="login-button">登录</button>
      </div>
      <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: "15651616098",
      password: "rlyp1234",
      errorMessage: "",
    };
  },
  methods: {
    async login() {
      try {
        const response = await fetch("http://127.0.0.1:5000/api/login", {
          method: "POST",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify({
            username: this.username,
            password: this.password,
          }),
        });

        const data = await response.json();
        if (response.ok) {
          console.log("登录成功")
          this.$router.push({ name: "DataView" });

        } else {
          this.errorMessage = data.message || "登录失败";
        }
      } catch (error) {
        this.errorMessage = "无法连接到服务器";
        console.error(error);
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #6a11cb, #2575fc);
}

.login-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  text-align: center;
  width: 100%;
  max-width: 400px;
}

.login-title {
  font-size: 1.5em;
  margin-bottom: 20px;
  color: #333;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.login-input {
  padding: 10px;
  font-size: 1em;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: border-color 0.3s;
}

.login-input:focus {
  border-color: #2575fc;
  outline: none;
}

.login-button {
  padding: 10px;
  font-size: 1em;
  background-color: #2575fc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover {
  background-color: #6a11cb;
}

.error {
  color: red;
  margin-top: 10px;
}
</style>
